package com.qfmy.webapp.tool;

import com.qfmy.model.entity.novel.Novel;
import com.qfmy.model.enums.NovelStatus;
import com.qfmy.model.vo.novel.NovelVo;
import com.qfmy.webapp.mapper.novel.NovelMapper;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 清风明月
 * @Package com.qfmy.web.app.tool
 * @date 2025/11/05
 * @description 操作小说的工具
 */
@Component
@SuppressWarnings("all")
public class NovelTools {

    /**
     * 注入小说Mapper
     */
    @Autowired
    private NovelMapper novelMapper;

    /**
     * 查询综合评分高的小说(也叫热门小说)
     */
    @Tool(name = "查询热门的小说")
    public List<NovelVo> getHotNovels() {
        //查询热门的小说
        List<Novel> novels = novelMapper.getHotNovelsPage(1, 5);
        //如果没有数据，则返回空列表
        if (novels == null || novels.isEmpty()) {
            return Collections.emptyList();
        }
        //转换对象
        return convertToNovel(novels);
    }

    /**
     * 根据小说的描述和类型查询小说
     */
    @Tool(name = "根据小说的描述或者描述或者字数或者作者查询小说")
    public List<NovelVo> searchNovels(@P("小说的描述或者描述或者字数或者作者") String keyword) {
        //根据关键字查询小说信息
        List<Novel> novels = novelMapper.searchNovels(keyword);
        //如果没有数据，则返回空列表
        if (novels == null || novels.isEmpty()) {
            return Collections.emptyList();
        }
        //转换对象
        return convertToNovel(novels);
    }

    /**
     * 根据小说的名称查询具体的小说信息
     */
    @Tool(name = "根据小说名称查询小说信息")
    public NovelVo getNovelsByName(@P("小说名称") String name) {
        //根据名称查询小说信息
        Novel novel = novelMapper.selectByNovelName(name);
        //如果没有数据，则返回空
        if (novel == null) {
            return null;
        }
        //创建集合并转换
        List<Novel> list = new ArrayList<>();
        list.add(novel);
        return convertToNovel(list).get(0);
    }

    /**
     * 转换实体为VO
     */
    private List<NovelVo> convertToNovel(List<Novel> novels) {
        if (novels == null || novels.isEmpty()) {
            return Collections.emptyList();
        }
        return novels.stream().map(novel -> {
            NovelVo novelVo = new NovelVo();
            BeanUtils.copyProperties(novel, novelVo);
            novelVo.setStatus(NovelStatus.getNameByCode(novel.getStatus()));
            return novelVo;
        }).collect(Collectors.toList());
    }
}